package com.lc.command;

import com.lc.protocol.DeviceError;

import org.json.JSONObject;
import java.lang.reflect.Method;

/**
 * Created by zhyioo on 2017/4/29.
 */

public class CommandReflecter implements ICommandDriver {

    protected Object _obj = null;

    protected Class<?> _classModule = null;

    public CommandReflecter() {}

    public CommandReflecter(Object obj) {
        Select(obj);
    }

    public boolean Select(Object obj) {
        _classModule = null;
        _obj = null;

        if(obj != null) {
            try {
                _classModule = Class.forName(obj.getClass().getName());
            } catch (Exception e) {
                return false;
            }
            _obj = obj;
        }

        return IsValid();
    }

    public boolean IsValid() {
        return _classModule != null;
    }

    @Override
    public boolean OnCommand(String cmd, JSONObject arg, JSONObject rlt) {
        if(_classModule == null) {
            CommandActuator.LogErr(rlt, DeviceError.ArgIsNullErr, "Class is null");
            return false;
        }

        Method method = null;
        try {
            method = _classModule.getMethod(cmd, JSONObject.class, JSONObject.class);
        } catch (Exception e) {
            e.printStackTrace();
            CommandActuator.LogErr(rlt, DeviceError.ArgErr, e.toString());
            return false;
        }

        boolean bOK = false;
        try {
            Object retObj = method.invoke(_obj, arg, rlt);
            bOK = Boolean.parseBoolean(retObj.toString());
            CommandActuator.LogErr(rlt, bOK ? DeviceError.Success : DeviceError.OperatorErr, "Method:" + cmd);
        } catch (Exception e) {
            e.printStackTrace();
            CommandActuator.LogErr(rlt, DeviceError.OperatorStatusErr, e.toString());
        }

        return bOK;
    }
}
